package jwei.apps;

import java.util.List;

import jwei.apps.db.StyleDb;
import jwei.apps.helpers.ImageService;
import jwei.apps.objects.Style;
import jwei.apps.zappos.ZapposSearchSimilar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class ProductSimilarActivity extends Activity {

    private ProgressDialog pd;

    private Button left, right;

    private ImageView product;

    private long styleId;

    private int index;

    private List<Style> similarProducts;

    private Style curStyle;

    // TODO bitmap cache?

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.product_similar_layout);

        Intent i = getIntent();
        styleId = i.getLongExtra("styleId", 0);

        left = (Button) findViewById(R.id.product_left_arrow);
        right = (Button) findViewById(R.id.product_right_arrow);
        product = (ImageView) findViewById(R.id.product_similar_img);

        left.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                index--;
                updateSimilarProduct();
            }

        });

        right.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                index++;
                updateSimilarProduct();
            }

        });

        product.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent i = new Intent(ProductSimilarActivity.this, ProductDetailsActivity.class);
                long productId = curStyle.getProductId();

                StyleDb sdb = StyleDb.getInstance();
                sdb.addStyle(getContentResolver(), curStyle);

                i.putExtra("productId", productId);
                i.putExtra("productName", curStyle.getProductName());
                i.putExtra("productUrl", curStyle.getProductUrl());
                i.putExtra("brandName", curStyle.getBrandName());
                i.putExtra("imageUrl", curStyle.getImageUrl());
                i.putExtra("styleId", curStyle.getStyleId());
                i.putExtra("price", curStyle.getPrice());
                startActivity(i);
            }

        });

        new GetSimilarProductsTask().execute(styleId);
    }

    private class GetSimilarProductsTask extends AsyncTask<Long, String, List<Style>> {

        @Override
        protected void onPreExecute() {
            pd = ProgressDialog.show(ProductSimilarActivity.this, "Getting Reviews",
                    "Please wait while we get reviews for this product...", true, false);
        }

        // param[0] is style id
        protected List<Style> doInBackground(Long... param) {
            long id = param[0];
            List<Style> ret = ZapposSearchSimilar.searchSimilarStyles(id);
            return ret;
        }

        protected void onProgressUpdate(String... progress) {
            pd.setMessage(progress[0]);
        }

        protected void onPostExecute(List<Style> products) {
            if (products.size() > 0) {
                // prepare bottom slider display
                index = 0;
                similarProducts = products;
                updateSimilarProduct();
            } else {
                Toast t = Toast.makeText(ProductSimilarActivity.this,
                        "Could not find similar items for this product - check back with Zappos in a bit!",
                        Toast.LENGTH_SHORT);
                t.show();
                product.setImageResource(R.drawable.empty_cart);
            }
            if (pd.isShowing()) {
                pd.dismiss();
            }
        }
    }

    private void updateSimilarProduct() {
        if (similarProducts == null) {
            Log.e("ProductSimilarActivity", "similar products list was null");
            return;
        }
        if (similarProducts.size() == 0) {
            Log.w("ProductSimilarActivity", "returned 0 similar products");
            return;
        }

        // set to loader first
        product.setImageResource(R.drawable.loader);

        // no negative mods allowed?
        if (index < 0) {
            index += similarProducts.size();
        }
        int i = index % similarProducts.size();

        curStyle = similarProducts.get(i);
        String imgUrl = curStyle.getImageUrl();
        new LoadImageTask().execute(imgUrl);
    }

    private class LoadImageTask extends AsyncTask<String, String, Bitmap> {

        @Override
        protected void onPreExecute() {
        }

        // param[0] is image url
        protected Bitmap doInBackground(String... param) {
            // get bitmap from url
            Bitmap bm = ImageService.getBitmapFromURL(param[0]);
            return bm;
        }

        protected void onProgressUpdate(String... progress) {
        }

        protected void onPostExecute(Bitmap bm) {
            if (bm != null) {
                product.setImageBitmap(bm);
            }
        }
    }
}
